{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Tune GPT2 to generate positive reviews\n",
    "> Optimise GPT2 to produce positive IMDB movie reviews using a BERT sentiment classifier as a reward function."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div style=\"text-align: center\">\n",
    "<img src='https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/gpt2_bert_training.png' width='600'>\n",
    "<p style=\"text-align: center;\"> <b>Figure:</b> Experiment setup to tune GPT2. The yellow arrows are outside the scope of this notebook, but the trained models are available through Hugging Face. </p>\n",
    "</div>\n",
    "\n",
    "\n",
    "In this notebook we fine-tune GPT2 (small) to generate positive movie reviews based on the IMDB dataset. The model gets the start of a real review and is tasked to produce positive continuations. To reward positive continuations we use a BERT classifier to analyse the sentiment of the produced sentences and use the classifier's outputs as rewards signals for PPO training."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Setup experiment"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Import dependencies"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%load_ext autoreload\n",
    "%autoreload 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install transformers trl wandb"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "from tqdm import tqdm\n",
    "import pandas as pd\n",
    "\n",
    "tqdm.pandas()\n",
    "\n",
    "from transformers import pipeline, AutoTokenizer\n",
    "from datasets import load_dataset\n",
    "\n",
    "from trl import PPOTrainer, PPOConfig, AutoModelForCausalLMWithValueHead\n",
    "from trl.core import LengthSampler"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Configuration"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "config = PPOConfig(\n",
    "    model_name=\"lvwerra/gpt2-imdb\",\n",
    "    learning_rate=1.41e-5,\n",
    "    log_with=\"wandb\",\n",
    ")\n",
    "\n",
    "sent_kwargs = {\"return_all_scores\": True, \"function_to_apply\": \"none\", \"batch_size\": 16}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import wandb\n",
    "\n",
    "wandb.init()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can see that we load a GPT2 model called `gpt2_imdb`. This model was additionally fine-tuned on the IMDB dataset for 1 epoch with the huggingface [script](https://github.com/huggingface/transformers/blob/master/examples/run_language_modeling.py) (no special settings). The other parameters are mostly taken from the original paper [\"Fine-Tuning Language Models from Human Preferences\"](\n",
    "https://arxiv.org/pdf/1909.08593.pdf). This model as well as the BERT model is available in the Huggingface model zoo [here](https://huggingface.co/models). The following code should automatically download the models."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Load data and models"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Load IMDB dataset\n",
    "The IMDB dataset contains 50k movie review annotated with \"positive\"/\"negative\" feedback indicating the sentiment.  We load the IMDB dataset into a DataFrame and filter for comments that are at least 200 characters. Then we tokenize each text and cut it to random size with the `LengthSampler`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Reusing dataset imdb (/home/leandro/.cache/huggingface/datasets/imdb/plain_text/1.0.0/2fdd8b9bcadd6e7055e742a706876ba43f19faee861df134affd7a3f60fc38a1)\n",
      "Loading cached processed dataset at /home/leandro/.cache/huggingface/datasets/imdb/plain_text/1.0.0/2fdd8b9bcadd6e7055e742a706876ba43f19faee861df134affd7a3f60fc38a1/cache-ff455473e884c6a3.arrow\n"
     ]
    }
   ],
   "source": [
    "def build_dataset(config, dataset_name=\"imdb\", input_min_text_length=2, input_max_text_length=8):\n",
    "    \"\"\"\n",
    "    Build dataset for training. This builds the dataset from `load_dataset`, one should\n",
    "    customize this function to train the model on its own dataset.\n",
    "\n",
    "    Args:\n",
    "        dataset_name (`str`):\n",
    "            The name of the dataset to be loaded.\n",
    "\n",
    "    Returns:\n",
    "        dataloader (`torch.utils.data.DataLoader`):\n",
    "            The dataloader for the dataset.\n",
    "    \"\"\"\n",
    "    tokenizer = AutoTokenizer.from_pretrained(config.model_name)\n",
    "    tokenizer.pad_token = tokenizer.eos_token\n",
    "    # load imdb with datasets\n",
    "    ds = load_dataset(dataset_name, split=\"train\")\n",
    "    ds = ds.rename_columns({\"text\": \"review\"})\n",
    "    ds = ds.filter(lambda x: len(x[\"review\"]) > 200, batched=False)\n",
    "\n",
    "    input_size = LengthSampler(input_min_text_length, input_max_text_length)\n",
    "\n",
    "    def tokenize(sample):\n",
    "        sample[\"input_ids\"] = tokenizer.encode(sample[\"review\"])[: input_size()]\n",
    "        sample[\"query\"] = tokenizer.decode(sample[\"input_ids\"])\n",
    "        return sample\n",
    "\n",
    "    ds = ds.map(tokenize, batched=False)\n",
    "    ds.set_format(type=\"torch\")\n",
    "    return ds"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "dataset = build_dataset(config)\n",
    "\n",
    "\n",
    "def collator(data):\n",
    "    return dict((key, [d[key] for d in data]) for key in data[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Load pre-trained GPT2 language models"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We load the GPT2 model with a value head and the tokenizer. We load the model twice; the first model is optimized while the second model serves as a reference to calculate the KL-divergence from the starting point. This serves as an additional reward signal in the PPO training to make sure the optimized model does not deviate too much from the original language model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model = AutoModelForCausalLMWithValueHead.from_pretrained(config.model_name)\n",
    "ref_model = AutoModelForCausalLMWithValueHead.from_pretrained(config.model_name)\n",
    "tokenizer = AutoTokenizer.from_pretrained(config.model_name)\n",
    "\n",
    "tokenizer.pad_token = tokenizer.eos_token"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Initialize PPOTrainer\n",
    "The `PPOTrainer` takes care of device placement and optimization later on:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ppo_trainer = PPOTrainer(config, model, ref_model, tokenizer, dataset=dataset, data_collator=collator)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Load BERT classifier\n",
    "We load a BERT classifier fine-tuned on the IMDB dataset."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "device = ppo_trainer.accelerator.device\n",
    "if ppo_trainer.accelerator.num_processes == 1:\n",
    "    device = 0 if torch.cuda.is_available() else \"cpu\"  # to avoid a `pipeline` bug\n",
    "sentiment_pipe = pipeline(\"sentiment-analysis\", model=\"lvwerra/distilbert-imdb\", device=device)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The model outputs are the logits for the negative and positive class. We will use the logits for positive class as a reward signal for the language model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[[{'label': 'NEGATIVE', 'score': 2.335048198699951},\n",
       "  {'label': 'POSITIVE', 'score': -2.726576566696167}]]"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "text = \"this movie was really bad!!\"\n",
    "sentiment_pipe(text, **sent_kwargs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[[{'label': 'NEGATIVE', 'score': -2.2947897911071777},\n",
       "  {'label': 'POSITIVE', 'score': 2.557039737701416}]]"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "text = \"this movie was really good!!\"\n",
    "sentiment_pipe(text, **sent_kwargs)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Generation settings\n",
    "For the response generation we just use sampling and make sure top-k and nucleus sampling are turned off as well as a minimal length."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "gen_kwargs = {\"min_length\": -1, \"top_k\": 0.0, \"top_p\": 1.0, \"do_sample\": True, \"pad_token_id\": tokenizer.eos_token_id}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Optimize model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Training loop"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The training loop consists of the following main steps:\n",
    "1. Get the query responses from the policy network (GPT-2)\n",
    "2. Get sentiments for query/responses from BERT\n",
    "3. Optimize policy with PPO using the (query, response, reward) triplet\n",
    "\n",
    "**Training time**\n",
    "\n",
    "This step takes **~2h** on a V100 GPU with the above specified settings."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "output_min_length = 4\n",
    "output_max_length = 16\n",
    "output_length_sampler = LengthSampler(output_min_length, output_max_length)\n",
    "\n",
    "\n",
    "generation_kwargs = {\n",
    "    \"min_length\": -1,\n",
    "    \"top_k\": 0.0,\n",
    "    \"top_p\": 1.0,\n",
    "    \"do_sample\": True,\n",
    "    \"pad_token_id\": tokenizer.eos_token_id,\n",
    "}\n",
    "\n",
    "\n",
    "for epoch, batch in tqdm(enumerate(ppo_trainer.dataloader)):\n",
    "    query_tensors = batch[\"input_ids\"]\n",
    "\n",
    "    #### Get response from gpt2\n",
    "    response_tensors = []\n",
    "    for query in query_tensors:\n",
    "        gen_len = output_length_sampler()\n",
    "        generation_kwargs[\"max_new_tokens\"] = gen_len\n",
    "        response = ppo_trainer.generate(query, **generation_kwargs)\n",
    "        response_tensors.append(response.squeeze()[-gen_len:])\n",
    "    batch[\"response\"] = [tokenizer.decode(r.squeeze()) for r in response_tensors]\n",
    "\n",
    "    #### Compute sentiment score\n",
    "    texts = [q + r for q, r in zip(batch[\"query\"], batch[\"response\"])]\n",
    "    pipe_outputs = sentiment_pipe(texts, **sent_kwargs)\n",
    "    rewards = [torch.tensor(output[1][\"score\"]) for output in pipe_outputs]\n",
    "\n",
    "    #### Run PPO step\n",
    "    stats = ppo_trainer.step(query_tensors, response_tensors, rewards)\n",
    "    ppo_trainer.log_stats(stats, batch, rewards)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Training progress\n",
    "If you are tracking the training progress with Weights&Biases you should see a plot similar to the one below. Check out the interactive sample report on wandb.ai: [link](https://app.wandb.ai/huggingface/trl-showcase/runs/1jtvxb1m/).\n",
    "\n",
    "<div style=\"text-align: center\">\n",
    "<img src='https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/gpt2_tuning_progress.png' width='800'>\n",
    "<p style=\"text-align: center;\"> <b>Figure:</b> Reward mean and distribution evolution during training. </p>\n",
    "</div>\n",
    "\n",
    "One can observe how the model starts to generate more positive outputs after a few optimisation steps.\n",
    "\n",
    "> Note: Investigating the KL-divergence will probably show that at this point the model has not converged to the target KL-divergence, yet. To get there would require longer training or starting with a higher initial coefficient."
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model inspection\n",
    "Let's inspect some examples from the IMDB dataset. We can use `model_ref` to compare the tuned model `model` against the model before optimisation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/leandro/miniconda3/envs/trl/lib/python3.9/site-packages/transformers/pipelines/base.py:1075: UserWarning: You seem to be using the pipelines sequentially on GPU. In order to maximize efficiency please use a dataset\n",
      "  warnings.warn(\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>query</th>\n",
       "      <th>response (before)</th>\n",
       "      <th>response (after)</th>\n",
       "      <th>rewards (before)</th>\n",
       "      <th>rewards (after)</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>Oh dear,</td>\n",
       "      <td>what are I saying?! I fast-forwarded through</td>\n",
       "      <td>I must say that I are hanging my head on this</td>\n",
       "      <td>-0.858954</td>\n",
       "      <td>-1.007609</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>I've seen</td>\n",
       "      <td>it, as well.&lt;br</td>\n",
       "      <td>three million dialogue throughout, and</td>\n",
       "      <td>1.996807</td>\n",
       "      <td>2.240883</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>Hi:&lt;br /&gt;&lt;br</td>\n",
       "      <td>/&gt;This movie is a turkey though when it comes to</td>\n",
       "      <td>/&gt;I also like that movie. It's so funny</td>\n",
       "      <td>-0.438191</td>\n",
       "      <td>2.415630</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>I'm a writer</td>\n",
       "      <td>and I'm not going to be asked to</td>\n",
       "      <td>, not a screenwriter. I've written</td>\n",
       "      <td>-0.655991</td>\n",
       "      <td>-0.724324</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>If you</td>\n",
       "      <td>absolutely love sensitive romance, the plot a...</td>\n",
       "      <td>are looking at the cinematography, the acting,</td>\n",
       "      <td>2.221309</td>\n",
       "      <td>0.148751</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>OMG this</td>\n",
       "      <td>casting cast. Obi cult breezy, this is</td>\n",
       "      <td>movie was totally wonderful, I it was the ide...</td>\n",
       "      <td>-1.533139</td>\n",
       "      <td>2.590190</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>It's</td>\n",
       "      <td>unrealistic; the guy who was supposed to be E...</td>\n",
       "      <td>a very good film. It reminds us about over</td>\n",
       "      <td>-2.097017</td>\n",
       "      <td>2.835831</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>There is a really</td>\n",
       "      <td>awful laptop game!&lt;br /&gt;&lt;br /&gt;I used to</td>\n",
       "      <td>interesting story that set us the journey. Th...</td>\n",
       "      <td>-2.341743</td>\n",
       "      <td>2.282939</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>This is</td>\n",
       "      <td>my favorite part about</td>\n",
       "      <td>a well thought well</td>\n",
       "      <td>2.554794</td>\n",
       "      <td>2.734139</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>Wasn't</td>\n",
       "      <td>Wasn't it clichéd?&lt;|endoftext|&gt;</td>\n",
       "      <td>anyone else interested in this movie? It's a ...</td>\n",
       "      <td>-1.790802</td>\n",
       "      <td>2.631960</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>This film is another of director Tim</td>\n",
       "      <td>Burton's masterpieces</td>\n",
       "      <td>Curry's best bombs</td>\n",
       "      <td>2.622917</td>\n",
       "      <td>2.544106</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>11</th>\n",
       "      <td>I thought this movie</td>\n",
       "      <td>was excellent. I actually laughed 6 times and...</td>\n",
       "      <td>was perfect, and I believe it's almost overlo...</td>\n",
       "      <td>2.548022</td>\n",
       "      <td>2.601913</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>12</th>\n",
       "      <td>This early John Wayne</td>\n",
       "      <td>films looked like an abandoned police beating</td>\n",
       "      <td>film is a realistic portrayal of what</td>\n",
       "      <td>-1.742279</td>\n",
       "      <td>2.609762</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>13</th>\n",
       "      <td>I was</td>\n",
       "      <td>given an experience-a big one, almost 25</td>\n",
       "      <td>very happy with all the reflections and this ...</td>\n",
       "      <td>2.250709</td>\n",
       "      <td>2.558540</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>14</th>\n",
       "      <td>Embarrassingly, I</td>\n",
       "      <td>am more at a strict conformity after getting ...</td>\n",
       "      <td>had never seen a movie before. There was one ...</td>\n",
       "      <td>-2.021666</td>\n",
       "      <td>-1.803383</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>15</th>\n",
       "      <td>I am a fan</td>\n",
       "      <td>of living on simple islands, and we have visi...</td>\n",
       "      <td>of many things and learned how to appreciate ...</td>\n",
       "      <td>1.791297</td>\n",
       "      <td>2.324461</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                                   query  \\\n",
       "0                               Oh dear,   \n",
       "1                              I've seen   \n",
       "2                           Hi:<br /><br   \n",
       "3                           I'm a writer   \n",
       "4                                 If you   \n",
       "5                               OMG this   \n",
       "6                                   It's   \n",
       "7                      There is a really   \n",
       "8                                This is   \n",
       "9                                 Wasn't   \n",
       "10  This film is another of director Tim   \n",
       "11                  I thought this movie   \n",
       "12                 This early John Wayne   \n",
       "13                                 I was   \n",
       "14                     Embarrassingly, I   \n",
       "15                            I am a fan   \n",
       "\n",
       "                                    response (before)  \\\n",
       "0        what are I saying?! I fast-forwarded through   \n",
       "1                                     it, as well.<br   \n",
       "2    />This movie is a turkey though when it comes to   \n",
       "3                    and I'm not going to be asked to   \n",
       "4    absolutely love sensitive romance, the plot a...   \n",
       "5              casting cast. Obi cult breezy, this is   \n",
       "6    unrealistic; the guy who was supposed to be E...   \n",
       "7             awful laptop game!<br /><br />I used to   \n",
       "8                              my favorite part about   \n",
       "9                     Wasn't it clichéd?<|endoftext|>   \n",
       "10                              Burton's masterpieces   \n",
       "11   was excellent. I actually laughed 6 times and...   \n",
       "12      films looked like an abandoned police beating   \n",
       "13           given an experience-a big one, almost 25   \n",
       "14   am more at a strict conformity after getting ...   \n",
       "15   of living on simple islands, and we have visi...   \n",
       "\n",
       "                                     response (after)  rewards (before)  \\\n",
       "0       I must say that I are hanging my head on this         -0.858954   \n",
       "1              three million dialogue throughout, and          1.996807   \n",
       "2             />I also like that movie. It's so funny         -0.438191   \n",
       "3                  , not a screenwriter. I've written         -0.655991   \n",
       "4      are looking at the cinematography, the acting,          2.221309   \n",
       "5    movie was totally wonderful, I it was the ide...         -1.533139   \n",
       "6          a very good film. It reminds us about over         -2.097017   \n",
       "7    interesting story that set us the journey. Th...         -2.341743   \n",
       "8                                 a well thought well          2.554794   \n",
       "9    anyone else interested in this movie? It's a ...         -1.790802   \n",
       "10                                 Curry's best bombs          2.622917   \n",
       "11   was perfect, and I believe it's almost overlo...          2.548022   \n",
       "12              film is a realistic portrayal of what         -1.742279   \n",
       "13   very happy with all the reflections and this ...          2.250709   \n",
       "14   had never seen a movie before. There was one ...         -2.021666   \n",
       "15   of many things and learned how to appreciate ...          1.791297   \n",
       "\n",
       "    rewards (after)  \n",
       "0         -1.007609  \n",
       "1          2.240883  \n",
       "2          2.415630  \n",
       "3         -0.724324  \n",
       "4          0.148751  \n",
       "5          2.590190  \n",
       "6          2.835831  \n",
       "7          2.282939  \n",
       "8          2.734139  \n",
       "9          2.631960  \n",
       "10         2.544106  \n",
       "11         2.601913  \n",
       "12         2.609762  \n",
       "13         2.558540  \n",
       "14        -1.803383  \n",
       "15         2.324461  "
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#### get a batch from the dataset\n",
    "bs = 16\n",
    "game_data = dict()\n",
    "dataset.set_format(\"pandas\")\n",
    "df_batch = dataset[:].sample(bs)\n",
    "game_data[\"query\"] = df_batch[\"query\"].tolist()\n",
    "query_tensors = df_batch[\"input_ids\"].tolist()\n",
    "\n",
    "response_tensors_ref, response_tensors = [], []\n",
    "\n",
    "#### get response from gpt2 and gpt2_ref\n",
    "for i in range(bs):\n",
    "    gen_len = output_length_sampler()\n",
    "    output = ref_model.generate(\n",
    "        torch.tensor(query_tensors[i]).unsqueeze(dim=0).to(device), max_new_tokens=gen_len, **gen_kwargs\n",
    "    ).squeeze()[-gen_len:]\n",
    "    response_tensors_ref.append(output)\n",
    "    output = model.generate(\n",
    "        torch.tensor(query_tensors[i]).unsqueeze(dim=0).to(device), max_new_tokens=gen_len, **gen_kwargs\n",
    "    ).squeeze()[-gen_len:]\n",
    "    response_tensors.append(output)\n",
    "\n",
    "#### decode responses\n",
    "game_data[\"response (before)\"] = [tokenizer.decode(response_tensors_ref[i]) for i in range(bs)]\n",
    "game_data[\"response (after)\"] = [tokenizer.decode(response_tensors[i]) for i in range(bs)]\n",
    "\n",
    "#### sentiment analysis of query/response pairs before/after\n",
    "texts = [q + r for q, r in zip(game_data[\"query\"], game_data[\"response (before)\"])]\n",
    "game_data[\"rewards (before)\"] = [output[1][\"score\"] for output in sentiment_pipe(texts, **sent_kwargs)]\n",
    "\n",
    "texts = [q + r for q, r in zip(game_data[\"query\"], game_data[\"response (after)\"])]\n",
    "game_data[\"rewards (after)\"] = [output[1][\"score\"] for output in sentiment_pipe(texts, **sent_kwargs)]\n",
    "\n",
    "# store results in a dataframe\n",
    "df_results = pd.DataFrame(game_data)\n",
    "df_results"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Looking at the reward mean/median of the generated sequences we observe a significant difference."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "mean:\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "rewards (before)    0.156629\n",
       "rewards (after)     1.686487\n",
       "dtype: float64"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "median:\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "rewards (before)   -0.547091\n",
       "rewards (after)     2.479868\n",
       "dtype: float64"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "print(\"mean:\")\n",
    "display(df_results[[\"rewards (before)\", \"rewards (after)\"]].mean())\n",
    "print()\n",
    "print(\"median:\")\n",
    "display(df_results[[\"rewards (before)\", \"rewards (after)\"]].median())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Save model\n",
    "Finally, we save the model and push it to the Hugging Face for later usage."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/leandro/miniconda3/envs/trl/lib/python3.9/site-packages/huggingface_hub/hf_api.py:1001: FutureWarning: `create_repo` now takes `token` as an optional positional argument. Be sure to adapt your code!\n",
      "  warnings.warn(\n",
      "Cloning https://huggingface.co/lvwerra/gpt2-imdb-pos-v2 into local empty directory.\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "a953a6d0c465432bbc39aca826d37aaf",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Upload file pytorch_model.bin:   0%|          | 32.0k/487M [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "remote: Enforcing permissions...        \n",
      "remote: Allowed refs: all        \n",
      "To https://huggingface.co/lvwerra/gpt2-imdb-pos-v2\n",
      "   369b075..28b9865  main -> main\n",
      "\n",
      "remote: Enforcing permissions...        \n",
      "remote: Allowed refs: all        \n",
      "To https://huggingface.co/lvwerra/gpt2-imdb-pos-v2\n",
      "   28b9865..42792ea  main -> main\n",
      "\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "('gpt2-imdb-pos-v2/tokenizer_config.json',\n",
       " 'gpt2-imdb-pos-v2/special_tokens_map.json',\n",
       " 'gpt2-imdb-pos-v2/vocab.json',\n",
       " 'gpt2-imdb-pos-v2/merges.txt',\n",
       " 'gpt2-imdb-pos-v2/added_tokens.json',\n",
       " 'gpt2-imdb-pos-v2/tokenizer.json')"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.save_pretrained(\"gpt2-imdb-pos-v2\", push_to_hub=True)\n",
    "tokenizer.save_pretrained(\"gpt2-imdb-pos-v2\", push_to_hub=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "env",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.12 (main, Mar 26 2022, 15:51:15) \n[Clang 13.1.6 (clang-1316.0.21.2)]"
  },
  "vscode": {
   "interpreter": {
    "hash": "4c8ff454cd947027f86954d72bf940c689a97dcc494eb53cfe4813862c6065fe"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
